﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Storage;
using Windows.Storage.Pickers;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using Windows.UI.Xaml.Media.Imaging;
using Windows.Storage.Streams;
using StudyTime_1.classes;


// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237

namespace StudyTime_1
{
    /// <summary>
    /// A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class quizMe : StudyTime_1.Common.LayoutAwarePage
    {

        public List<quizQuest> quizList = new List<quizQuest>();

        private List<int> questionTracker = new List<int>();
        private List<int> questionTracker2 = new List<int>();
        private List<int> prevTracker = new List<int>();
      //  public List<reviewClass> reviewList = new List<reviewClass>();
        public StorageFile storage;

        int questCounter = 0;
        //int recursCounter = 0;
        int currPage = 0;
        int scoreCount = 0;
        int totalSize;
        int randomNumber;
        int backTracker = 1;

        bool listCreated = false;
        public static bool reviewYes = false;
        bool prevSelected = false;

        //private string fileName;
        //private string filePath;

        private string actualAnswerText;
        private string userAnswerText;

        Uri blankURI = new Uri("",UriKind.Relative);
        static Random ran = new Random();


        public quizMe()
        {
            this.InitializeComponent();

            

            answer.ItemsSource = new List<string> { "A", "B", "C", "D" };
            answer.SelectedIndex = 0;

            checkset();
        }

        private void checkset()
        {
            if (App.fileInSet == true)
            {
                var st = App.fileInStorage as StorageFile;

                storage = st;

               // loadData(quizList);

                App.fileInSet = false;

            }
        }
        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
        }

        //protected override void OnNavigatedTo(NavigationEventArgs e)
        //{

        //    if (e.Parameter != null)
        //    {
        //        var parm = e.Parameter as StorageFile;
        //        storage = parm;

        //        loadData(quizList);
        //    }
        //}

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
        }

         private void loadData()
        {

            //convLength = 0;
            
            quizList.Clear();
            App.reviewList.Clear();
            currPage = 0;
            questionTracker.Clear();
            questionTracker2.Clear();
            randomNumber = 0;
            questCounter = 0;
          
            foreach (quizQuest quizQuest in App.quizList)
            {
                questionTracker.Add(questCounter);
                questCounter++;
                quizList.Add(quizQuest);
            }

            if (App.randomQuizQuest == true)
            {
                getRandomNumber();
                setText(randomNumber);

                if (quizList[randomNumber].picture != null)
                {
                    setImage(randomNumber, false);
                }
                else
                {
                    setImage(randomNumber, true);
                }

                listCreated = true;


                reviewBut.Content = scoreCount + " of " + quizList.Count();
            }

            else
            {
                questions.Text = quizList[0].question.ToString();
                questions.Text = quizList[randomNumber].question.ToString() + Environment.NewLine + Environment.NewLine + "A: " + quizList[randomNumber].answerA + Environment.NewLine + Environment.NewLine + "B: " +
            quizList[randomNumber].answerB + Environment.NewLine + Environment.NewLine + "C: " + quizList[randomNumber].answerC +
            Environment.NewLine + Environment.NewLine + "D: " + quizList[randomNumber].answerD;

                if (quizList[currPage].picture != null)
                {
                    setImage(currPage, false);
                }
                else
                {
                    setImage(currPage, true);
                }

                listCreated = true;


                reviewBut.Content = scoreCount + " of " + quizList.Count();

            }
            
 

            



            //        }
            //        catch (SerializationException e)
            //        {
            //            errorBox.Text = "Could not Load:" + e;
            //        }
            //        catch (IOException e)
            //        {
            //            errorBox.Text = "Could not Load:" + e;
            //        }
            //    }
            //}
        }

        private void back_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.GoBack();
        }

        async private void selection_Click(object sender, RoutedEventArgs e)
        {

           
            

            await openHelper.openPicker(false);

            if (App.quizList.Count > 0)
            {

                loadData();
            }


            //{
            //    {

            //        FileOpenPicker openPicker = new FileOpenPicker();
            //        openPicker.ViewMode = PickerViewMode.List;
            //        openPicker.SuggestedStartLocation = PickerLocationId.Downloads;
            //        openPicker.FileTypeFilter.Add(".quizxml");
                   
                    
            //        storage = await openPicker.PickSingleFileAsync();

            //        if (null != storage)
            //        {
            //            // Application now has read/write access to the picked file
            //            fileName = storage.Name;
            //            filePath = storage.Path;
            //            loadData(quizList);
            //            //questions.Text = fileName + " Click Load if this is the correct File";

            //        }
            //        else
            //        {
            //            questions.Text = "File was not returned";
            //        }
            //    }


            //}
        }

        private void last_Click(object sender, RoutedEventArgs e)
        {

            prevSelected = true;

            if (imgScroll.Visibility == Visibility.Visible)
            {
                imgScroll.Visibility = Visibility.Collapsed;
                imagebttn.Content = "Image";
            }

            int i = questionTracker2.Count - backTracker;
            

            if (listCreated == true)
            {
                if (currPage <= 0)
                {
                    currPage = -1;
                    questions.Text = "Beginning of Quiz, press next to continue.";
                    setImage(currPage, true);
                }


                else if (currPage <= quizList.Count - 1 && currPage > -1)
                {
                    currPage--;
                    if (App.randomQuizQuest == true)
                    {
                        if (questionTracker2.Count - 2 >= 0)
                        {
                            int tempVar = questionTracker2[questionTracker2.Count - 1];

                                prevTracker.Add(tempVar);
                                questionTracker2.Remove(tempVar);
                                setText(tempVar);
                                setImage(tempVar, false);
                        }
                      
                    }
                    else
                    {
                        setText(currPage);
                        setImage(currPage, false);
                    }
                    }
                
        
                           
          

                        // backTracker--;
                        //questions.Text = quizList[currPage].question.ToString();
                        //questions.Text = quizList[randomNumber].question.ToString() + Environment.NewLine + Environment.NewLine + "A: " + quizList[randomNumber].answerA + Environment.NewLine + Environment.NewLine + "B: " +
                        //    quizList[randomNumber].answerB + Environment.NewLine + Environment.NewLine + "C: " + quizList[randomNumber].answerC +
                        //    Environment.NewLine + Environment.NewLine + "D: " + quizList[randomNumber].answerD;
                        //setImage(currPage, false);

                else if(currPage == quizList.Count)
                {
                    currPage--;

                    if (App.randomQuizQuest == true)
                    {

                        int tempVar = questionTracker2[questionTracker2.Count - 1];

                        prevTracker.Add(questionTracker2[tempVar]);
                        questionTracker2.Remove(tempVar);
                        setText(tempVar);
                        setImage(tempVar, false);

                    }
                    else
                    {
                        setText(currPage);
                        setImage(currPage, false);
                    }

                    //questions.Text = quizList[currPage].question.ToString();
                    //questions.Text = quizList[randomNumber].question.ToString() + Environment.NewLine + Environment.NewLine + "A: " + quizList[randomNumber].answerA + Environment.NewLine + Environment.NewLine + "B: " +
                    //    quizList[randomNumber].answerB + Environment.NewLine + Environment.NewLine + "C: " + quizList[randomNumber].answerC +
                    //    Environment.NewLine + Environment.NewLine + "D: " + quizList[randomNumber].answerD;
                   
                    

                }


                else 
                {
                    //questions.Text = quizList[0].question.ToString();
                    //questions.Text = quizList[randomNumber].question.ToString() + Environment.NewLine + Environment.NewLine + "A: " + quizList[randomNumber].answerA + Environment.NewLine + Environment.NewLine + "B: " +
                    //    quizList[randomNumber].answerB + Environment.NewLine + Environment.NewLine + "C: " + quizList[randomNumber].answerC +
                    //    Environment.NewLine + Environment.NewLine + "D: " + quizList[randomNumber].answerD;

                    if (App.randomQuizQuest == true)
                    {
                        int tempVar = questionTracker2[questionTracker2.Count - 2];

                        prevTracker.Add(questionTracker2[i]);
                        questionTracker2.Remove(tempVar);

                        setText(tempVar);
                        setImage(tempVar, false);
                    }
                    else
                    {
                        setText(currPage);
                        setImage(currPage, false);
                    }
                    //answer.Text = "";
                }
            }
            else
            {
                errorBox.Text = "Please load a Quiz.";
            }





        }

        private void next_Click(object sender, RoutedEventArgs e)
        {
            next_question();
        }


        private void check_Click(object sender, RoutedEventArgs e)
        {

           // getRandomNumber();

            if (App.randomQuizQuest == true)
            {

                if (imgScroll.Visibility == Visibility.Visible)
                {
                    imgScroll.Visibility = Visibility.Collapsed;
                    imagebttn.Content = "Image";
                }

                if (listCreated == true && randomNumber <= quizList.Count - 1)
                {
                    string temp = answer.SelectedItem.ToString();

                    if (temp.Equals(quizList[randomNumber].answer.ToString(), StringComparison.CurrentCultureIgnoreCase))
                    {

                        scoreCount++;
                        reviewBut.Content = scoreCount + " of " + quizList.Count();
                        errorBox.Text = "Thats right!";
                        next_question();
                    }
                    else
                    {
                        reviewClass revMe = new reviewClass();
                        getActual(quizList[randomNumber].answer, temp);

                        revMe.actualAnswer = actualAnswerText;
                        revMe.origQuestion = quizList[randomNumber].question.ToString();
                        revMe.yourAnswer = userAnswerText;
                        revMe.picture = quizList[randomNumber].picture;

                        App.reviewList.Add(revMe);

                        reviewBut.Content = scoreCount + " of " + quizList.Count();
                        errorBox.Text = "That is incorrect.";
                        next_question();
                    }
                }
                else
                {
                    errorBox.Text = "Please load a Quiz.";
                }
            }
            else
            {
                if (imgScroll.Visibility == Visibility.Visible)
                {
                    imgScroll.Visibility = Visibility.Collapsed;
                    imagebttn.Content = "Image";
                }

                if (listCreated == true && currPage <= quizList.Count - 1)
                {
                    string temp = answer.SelectedItem.ToString();

                    if (temp.Equals(quizList[currPage].answer.ToString(), StringComparison.CurrentCultureIgnoreCase))
                    {

                        scoreCount++;
                        reviewBut.Content = scoreCount + " of " + quizList.Count();
                        errorBox.Text = "Thats right!";
                        next_question();
                    }
                    else
                    {
                        reviewClass revMe = new reviewClass();
                        getActual(quizList[currPage].answer, temp);

                        revMe.actualAnswer = actualAnswerText;
                        revMe.origQuestion = quizList[currPage].question.ToString();
                        revMe.yourAnswer = userAnswerText;
                        revMe.picture = quizList[currPage].picture;

                        App.reviewList.Add(revMe);

                        reviewBut.Content = scoreCount + " of " + quizList.Count();
                        errorBox.Text = "That is incorrect.";
                        next_question();
                    }
                }
                else
                {
                    errorBox.Text = "Please load a Quiz.";
                }
            }

        }

        private void Grid_Loaded_1(object sender, RoutedEventArgs e)
        {
            ////Storyboard sb = this.FindName("quizMeStory") as Storyboard;
            //if (sb != null)
            //{
            //    sb.Begin();
            //}
        }

       async private void next_question()
        {
           // getRandomNumber();

            if (imgScroll.Visibility == Visibility.Visible)
            {
                imgScroll.Visibility = Visibility.Collapsed;
                imagebttn.Content = "Image";
            }



            if (listCreated == true)
            {

                if (prevSelected == false)
                {
                    currPage++;

                    if (currPage < quizList.Count)
                    {
                        if (App.randomQuizQuest == true)
                        {
                            //** IN TESTING Will Only happen when randomQuizQuest is set to true **//
                            getRandomNumber();
                            setText(randomNumber);

                            setImage(randomNumber, false);


                        }
                        else
                        {

                            

                            questions.Text = quizList[currPage].question.ToString();
                            questions.Text = quizList[currPage].question.ToString() + Environment.NewLine + Environment.NewLine + "A: " + quizList[currPage].answerA + Environment.NewLine + Environment.NewLine + "B: " +
                                quizList[currPage].answerB + Environment.NewLine + Environment.NewLine + "C: " + quizList[currPage].answerC +
                                Environment.NewLine + Environment.NewLine + "D: " + quizList[currPage].answerD;

                            if (quizList[currPage].picture != null)
                            {
                                setImage(currPage, false);
                            }
                            else
                            {
                                setImage(currPage, true);
                            }
                            
                        }
                        
                        //answer.Text = "";
                    }
                    else
                    {
                        //randomNumber = quizList.Count;
                        questions.Text = "End of Quiz, review by clicking your score.";
                        setImage(randomNumber, true);
                        await classes.messages.setMssg("review");
                        if (reviewYes == true)
                        {
                            if (App.reviewList.Count != 0)
                            {
                                setScoreInfo();
                                this.Frame.Navigate(typeof(Review1));

                            }
                            else
                            {
                                errorBox.Text = "This button is used for review, you must go through a quiz first.";
                            }
                        }
                    }
                }
                else
                {

                    if (prevTracker.Count > 0)
                    {
                        int tempVar = prevTracker[prevTracker.Count - 1];

                        prevTracker.Remove(tempVar);
                        questionTracker2.Add(tempVar);

                        setText(tempVar);
                    }
                    else
                    {
                        prevSelected = false;
                        next_question();
                    }
                    
                }
            }
            else
            {
                errorBox.Text = "Please Select a Quiz.";
            }
        }

/***** Testing random quiz question *****/
        private void getRandomNumber()
        {
            

            totalSize = questionTracker.Count;

            int setcount = quizList.Count / 2;
             randomNumber = ran.Next(totalSize);

            if (questionTracker.Count < setcount && questionTracker.Count != 0 || totalSize < 6)
            {
                currPage++;
                int grr = questionTracker[0];
                randomNumber = questionTracker[0];
                questionTracker.Remove(grr);
            }
            else if (questionTracker.Count >= setcount)
            {
                if (questionTracker2.Contains(randomNumber))
                {
                    getRandomNumber();
                }
                else
                {
                    currPage++;
                    questionTracker.Remove(randomNumber);
                    questionTracker2.Add(randomNumber);
                }

            }

            else
            {
                string s = "";
            }

           
        }
  

         private void reviewBut_Click(object sender, RoutedEventArgs e)
        {
            if (App.reviewList.Count != 0)
            {
                setScoreInfo();
                this.Frame.Navigate(typeof(Review1));
                setScoreInfo();
            }
            else
            {
                errorBox.Text = "This button is used for review, you must go through a quiz first.";
            }
        }
        private void getActual(string answer, string userAnswer)
        {

            if (App.randomQuizQuest == true)
            {

                switch (answer.ToLowerInvariant())
                {
                    case "a":
                        actualAnswerText = quizList[randomNumber].answerA;
                        break;
                    case "b":
                        actualAnswerText = quizList[randomNumber].answerB;
                        break;
                    case "c":
                        actualAnswerText = quizList[randomNumber].answerC;
                        break;
                    case "d":
                        actualAnswerText = quizList[randomNumber].answerD;
                        break;
                }

                switch (userAnswer.ToLowerInvariant())
                {
                    case "a":
                        userAnswerText = quizList[randomNumber].answerA;
                        break;
                    case "b":
                        userAnswerText = quizList[randomNumber].answerB;
                        break;
                    case "c":
                        userAnswerText = quizList[randomNumber].answerC;
                        break;
                    case "d":
                        userAnswerText = quizList[randomNumber].answerD;
                        break;
                }
            }
            else
            {

                switch (answer.ToLowerInvariant())
                {
                    case "a":
                        actualAnswerText = quizList[currPage].answerA;
                        break;
                    case "b":
                        actualAnswerText = quizList[currPage].answerB;
                        break;
                    case "c":
                        actualAnswerText = quizList[currPage].answerC;
                        break;
                    case "d":
                        actualAnswerText = quizList[currPage].answerD;
                        break;
                }

                switch (userAnswer.ToLowerInvariant())
                {
                    case "a":
                        userAnswerText = quizList[currPage].answerA;
                        break;
                    case "b":
                        userAnswerText = quizList[currPage].answerB;
                        break;
                    case "c":
                        userAnswerText = quizList[currPage].answerC;
                        break;
                    case "d":
                        userAnswerText = quizList[currPage].answerD;
                        break;
                }
            }
        }

        //async private void setImage(int image,bool end)
        //{
        //    byte[] tmp = quizList[image].picture;
        //    byte[] blank = new byte[1];

     
        //        BitmapImage tmpImg = new BitmapImage();

        //        var stream = new InMemoryRandomAccessStream();

        //        using (var writer = new DataWriter(stream))
        //        {
        //            if (end == false)
        //            {
        //            writer.WriteBytes(tmp);
        //            await writer.StoreAsync();
        //            writer.DetachStream();
        //            }
        //            else
        //            {
        //            writer.WriteBytes(blank);
        //            await writer.StoreAsync();
        //            writer.DetachStream();
        //            }
        //        }
        //        stream.Seek(0);
        //        tmpImg.SetSource(stream);

        //        quizImage.Source = tmpImg;
        //    }


        async private void setImage(int image,bool end)
        {
            byte[] tmp = new byte[1]; 
            byte[] blank = new byte[1]; 

            if (end == false)
            {
                 tmp = quizList[image].picture;
            }
            else
            {
                blank = new byte[1];
            }

            BitmapImage tmpImg = new BitmapImage();

            var stream = new InMemoryRandomAccessStream();

            using (var writer = new DataWriter(stream))
            {
                if (end == false && tmp != null)
                {
                    writer.WriteBytes(tmp);
                    await writer.StoreAsync();
                    writer.DetachStream();
                    imagebttn.IsEnabled = true;
                }
                else
                {
                    writer.WriteBytes(blank);
                    await writer.StoreAsync();
                    writer.DetachStream();
                    imagebttn.IsEnabled = false;
                }
            }
            stream.Seek(0);
            tmpImg.SetSource(stream);
            
            quizImage.Source = tmpImg;
           
           await stream.FlushAsync();
        }

        private void imagebttn_Click(object sender, RoutedEventArgs e)
        {

            if (imgScroll.Visibility == Visibility.Visible)
            {   
                popoutSB.Begin();
                imgScroll.Visibility = Visibility.Collapsed;
                imagebttn.Content = "Image";
                
            }
            else
            {
                imgScroll.Visibility = Visibility.Visible;
                imagebttn.Content = "back";
                popinSB.Begin();
            }

        }

       async private void setScoreInfo()
        {
            prevScores scoreSet = new prevScores();
            int sc1 = App.reviewList.Count - 1;
            int sc2 = App.quizList.Count - 1;
            scoreSet.score = sc1 + " of " + sc2;
           
            scoreSet.fileName = App.quizFile.Name;
            scoreSet.fileLocation = App.quizFile.Path;

            if (App.previousScores.Contains(scoreSet))
            {
                App.previousScores.Remove(scoreSet);
                App.previousScores.Add(scoreSet);
            }
            else
            {
                App.previousScores.Add(scoreSet);
            }

           await serializer.writeScoreXML();

        }

        private void setText(int i)
        {
            questions.Text = quizList[i].question.ToString() + Environment.NewLine + Environment.NewLine + "A: " + quizList[i].answerA + Environment.NewLine + Environment.NewLine + "B: " +
            quizList[i].answerB + Environment.NewLine + Environment.NewLine + "C: " + quizList[i].answerC +
            Environment.NewLine + Environment.NewLine + "D: " + quizList[i].answerD;
        }
        
    }
}
